<template>
  <div class="search-box">
    <el-autocomplete
      class="search-input"
      v-model="search"
      :fetch-suggestions="querySearch"
      placeholder="实体名称"
      @select="handleSelect"
      size="small"
      value-key="name"
    >
      <i class="el-icon-search el-input__icon" slot="prefix"></i>
    </el-autocomplete>
    <el-button class="search-btn" type="primary" size="small" @click="handleSearch">搜索</el-button>
    <el-button class="reset-btn" type="primary" size="small" @click="search = ''">重置</el-button>
  </div>
</template>

<script>
import EventBus from '../EventBus'
import Bus from '../EventBus/events'

export default {
  name: 'Search',
  data() {
    return {
      search: '',
      nodes: []
    }
  },
  mounted() {
    EventBus.$on(Bus.GRAPH_CHANGE, ({ nodes }) => {
      this.nodes = nodes
    })
  },
  methods: {
    querySearch(queryString, cb) {
      // console.log(queryString)
      if (queryString === '') {
        cb([])
      } else {
        let nodes = this.nodes
        // console.log(nodes)
        let results = queryString ? nodes.filter(node => node.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0) : nodes
        cb(results)
      }
    },
    handleSelect(item) {
      EventBus.$emit(Bus.SEARCH_SELECT, {
        node: item
      })
      // console.log(item)
    },
    handleSearch() {
      const { search, nodes } = this
      nodes.forEach((node) => {
        if (node.name === search) {
          EventBus.$emit(Bus.SEARCH_SELECT, {
            node: node
          })
        }
      })
      this.$message('对不起，没有该节点!!!');
    }
  }
}
</script>

<style lang="less">
.search-box {
  position: absolute;
  top: 10px;
  left: 10px;

  display: flex;
  align-items: center;

  .search-input {
    width: 240px;
    
    .el-input {
      font-size: 14px;

      input.el-input__inner {
        height: 34px;
        color: white;
        background: #0d245e;
        border-color: #325fd6;
      }
    }
  }

  .search-btn {
    margin-left: 4px;
    font-size: 14px;
    background-color: #3a72ff;
  }

  .reset-btn {
    font-size: 14px;
    background-color: #325fd6;
  }
}
</style>